<?php


namespace App\Repositories;

use App\Services\Draw\DrawConst\CacheKey;
use App\Services\Draw\Enum\DrawEnum;
use App\Exceptions\BasicException;
use Illuminate\Support\Facades\DB;

//补池处理逻辑 + 大礼物阈值配置处理逻辑 + 其他共用方法
class AddPoolRepository
{
    protected $game_type;
    protected $is_add_pool;
    protected $poolUserModel;
    protected $poolGroupModel;
    protected $poolPrizeModel;
    protected $poolConfigModel;
    protected $checkModel;
    protected $checkRecordModel;
    protected $giftConfigModel;
    protected $giftTemplateModel;
    protected $addPoolConfigModel;
    protected $addPoolAccountModel;
    protected $addPoolAccountRecordModel;
    protected $appointGiftModel;
    protected $set_type;
    protected $redis;
    protected $gameLockTime = 20;
    protected $wholePrefix = 'whole_game:';

    public const USER_GAME_CHECK_NUM = 'game_check_num:%s';


    public function __construct()
    {
        //通用
        $this->game_type = 2;//数据库字段废弃，为避免报错将值设置为2
        $this->is_add_pool = app('model_config')->getValue('IS_ADD_POOL');

        //分类开始
        $this->set_type = 'frag';
        $this->poolUserModel = app('model_frag_pool_user');
        $this->poolGroupModel = app('model_frag_pool_group');
        $this->poolPrizeModel = app('model_frag_pool_prize');
        $this->poolConfigModel = app('model_frag_pool_config');
        $this->checkModel = app('model_frag_draw_check');
        $this->checkRecordModel = app('model_frag_draw_check_record');
        $this->giftConfigModel = app('model_frag_gift_config');
        $this->giftTemplateModel = app('model_frag_gift_template');
        $this->addPoolConfigModel = app('model_frag_draw_add_pool_config');
        $this->addPoolAccountModel = app('model_frag_draw_add_pool_account');
        $this->addPoolAccountRecordModel = app('model_frag_draw_add_pool_account_record');
        $this->appointGiftModel = app('model_frag_appoint_gift');
        $this->redis = app('redis')->connection('game');
    }

    public function start()
    {
        return $this->is_add_pool;
    }

    //创建下一个池子时，判断是否需要将补充补池金额
    public function checkPool($tag, $game_type, $group_id)
    {
        $redis = $this->redis;
        if ($tag == 'public') {
            //每轮清空用户的游戏判定次数  必须公共池
            $user_game_check_num_key = sprintf(self::USER_GAME_CHECK_NUM, $this->set_type);
            $redis->del($user_game_check_num_key);
        }

        $redis_key = $this->set_type.':'. $tag . '_'. $group_id .'_lock';
        if (!$redis->set($redis_key, 'lock', 'ex', $this->gameLockTime, 'nx')) {
            return false;
        }
        $game_type = $this->game_type;
        //修正池规则不控制补池金额增加减少
        //if (!$this->is_add_pool) {
        //    return false;
        //}
        $data = $this->addPoolConfigModel->checkPool($tag, $game_type, $group_id);
        if ($data['add_money'] > 0) {
            $this->addPoolAccountRecordModel->addRecord([
                'game_type' => $game_type,
                'add_money' => $data['add_money'],
                'config_id' => $data['config_id'],
            ]);
        }
    }

    //指定补偿
    public function appointCompensate($user_id)
    {
        /*$appoint_gift = $this->appointGiftModel
            ->with('gift:id,price,name,picture')
            ->where(['user_id' => $user_id, 'is_valid' => 1, 'type' => 1])->first();*/
        if (empty($appoint_gift)) {
            return [];
        }
        $gift_info = $appoint_gift->gift->toArray();
        $gift_template_id = $this->giftTemplateModel
            ->where(['gift_id' => $gift_info['id']])->value('id');
        if (empty($gift_template_id)) {
            return [];
        }
        $gift_info['gift_template_id'] = $gift_template_id;
        $gift_info['appoint_gift_id'] = $appoint_gift->id;
        return $gift_info;
    }

    //保底礼物判定  受礼物阈值影响 「废弃」
    public function check_guaranteed($user, $config_key, $cachePrefix, $poolGroup)
    {
        $userId = $user->user_id;
        $guaranteed_data = explode(',', app('model_config')->getValue($config_key));
        $draw_count = $guaranteed_data[0] ?? 0;
        $give_gift_price_min = $guaranteed_data[2] ?? 0;
        $give_gift_price_max = $guaranteed_data[3] ?? 0;
        $gift_info = [];
        if (empty($guaranteed_data) || empty($draw_count) || empty($give_gift_price_min) || empty($give_gift_price_max)) {
            return $gift_info;
        }
        $redis = $this->redis;
        $redis_key = $cachePrefix.'guaranteed';
        $user_draw_count = $redis->hget($redis_key, $userId);
        // 触发保底机制
        if ($user_draw_count >= $draw_count) {
            $prize_table_name = $this->poolPrizeModel->getTable();
            $template_table_name = $this->giftTemplateModel->getTable();
            $group_id = $poolGroup->group_id;
            $no_draw_template_ids = $this->checkBigGift($userId);
            $compare_template_info = $this->giftTemplateModel->with('gift:id,price,name,picture')
                ->whereNotIn('id', $no_draw_template_ids)
                ->whereHas('gift', function ($query) use ($give_gift_price_min, $give_gift_price_max) {
                $query->where('price', '>=', $give_gift_price_min)->where('price', '<=', $give_gift_price_max);
            })->whereExists(function ($query) use ($prize_table_name, $template_table_name, $group_id) {
                $query->from($prize_table_name)
                    ->whereRaw("
                    {$prize_table_name}.count > 0 and 
                    {$prize_table_name}.group_id = {$group_id} and 
                    {$prize_table_name}.gift_template_id = $template_table_name.id
                    ");
            })->get()->toArray();
            if (empty($compare_template_info)) {
                return $gift_info;
            }
            $template_info = $compare_template_info[array_rand($compare_template_info)];
            $gift_info = $template_info['gift'];
            $gift_info['gift_template_id'] = $template_info['id'];
            $gift_info['appoint_gift_id'] = $this->appointGiftModel->insertGetId([
                'user_id' => $userId, 'gift_id' => $gift_info['id'], 'type' => 2, 'is_valid' => 1
            ]);
        }
        return $gift_info;


    }

    /**
     * 根据规则 进行修正
     * @param $user_id
     * @param $game_type  游戏类型
     * @param $tag  奖池类型
     * @return array
     */
    public function grantCompensate($user_id, $game_type, $tag)
    {
        $game_type = $this->game_type;
        $default_result = ['status' => false];
        if (!$this->is_add_pool) {
            return $default_result;
        }
        // 判定是否有补偿
        $result = $this->checkGame($user_id, $game_type, $tag);
        if (!$result['status']) {
            return $result;
        }
        // 礼物补偿
        if (!empty($result['gift_info'])) {
            $game_type_money = $this->addPoolAccountModel->where('game_type', $game_type)->value('money');
            $gift_template_id = $this->giftTemplateModel
                ->where(['gift_id' => $result['gift_info']['id']])->value('id');
            //补偿礼物判断，补池金额充足才补偿
            if (empty($gift_template_id) || $game_type_money < $result['gift_info']['price']) {
                $result['gift_info'] = [];
                if ($result['type'] == 2) {//亏损判断
                    return $default_result;
                }
            } else {
                $result['gift_info']['gift_template_id'] = $gift_template_id;
            }
            //判定用户是否可以拿到此次补偿的礼物
            // 1.本次盈亏为负数且有礼物补偿、 2.本轮判定不能超过设定的值 3.总判定略过
            $redis = $this->redis;
            $user_game_check_num_key = sprintf(self::USER_GAME_CHECK_NUM, $this->set_type);
            $game_check_num = $this->poolConfigModel->where('id', 1)->value('game_check_num');
            if (!$result['is_whole'] && $result['type'] == 2 && $game_check_num > 0
                && $redis->zscore($user_game_check_num_key, $user_id) >= $game_check_num) {
                return $default_result;
            }
            $redis->zincrby($user_game_check_num_key, 1, $user_id);
        }

        return $result;
    }

    /**
     * 游戏判定
     * param $user_id
     * param $game_type  1.航海 2.萌兽盲盒
     * param $tag  奖池类型
     * 返回
     */
    public function checkGame($user_id, $game_type, $tag)
    {
        $game_type = $this->game_type;
        $result = [
            'status' => false,
        ];

        $pool_user = $this->redis->hgetall($this->set_type.':' . CacheKey::USER_WEEK_PUT_RECORD . ":$user_id" . "_" . date("Y-W"));
        //根据游戏类型对应的用户表 查询用户的盈亏
//        $pool_user = $this->poolUserModel->where('user_id', $user_id)->first();
        if (empty($pool_user)) {
            return $result;
        }
        //周累计盈亏
        $diff = $pool_user['output'] - $pool_user['input'];
        if ($diff >= 0) {
            $where = ['type' => 1, ['money', '<=', $diff]];
            $desc = 'desc';//正数金额由大到小 8000 3000
        } else {
            $where = ['type' => 2, ['money', '>=', $diff]];
            $desc = 'asc';//负数金额由小到大 -8000 -3000
        }

        //查询所有符合条件的配置，根据是否可重复is_repeat判断结果
        $check_data = $this->checkModel->where($where)->with('gift:id,price,name,picture')->orderBy('money', $desc)->get()->toArray();

        if (!empty($check_data)) {
            $where = ['user_id' => $user_id, 'game_type' => $game_type];
            $check_record = $this->checkRecordModel->where($where)->distinct()->pluck('check_id');
            foreach ($check_data as $check) {
                //不是重复触发
                if(!$check['is_repeat']) {
                    $is_exist = $check_record->contains($check['id']);
                    if ($is_exist) {
                        continue;
                    }
                }
                //防止后台的配置经过更改、记录最初值
                $result = [
                    'status' => true,
                    'gift_info' => $check['gift'] ?: [],
                    'count' => $check['count'],
                    'check_id' => $check['id'],
                    'money' => $check['money'],
                    'type' => $check['type'],
                    'is_repeat' => $check['is_repeat'],
                    'clear_money' => 0,
                    'is_whole' => 0,
                ];
                break;
            }
        }

        //游戏盈利判定、当盈利金额达到设置的止盈金额时，将修正池次数清0
        //没有达到上面model_draw_check的游戏判定也触发
        if ($tag == DrawEnum::POOL_TYPE_SUP) {
            $clear_money = $this->poolConfigModel->where('id', 1)->value('clear_money');
            if (!empty($clear_money) && $diff <= $clear_money) {
                $result['status'] = true;
                $result['clear_money'] = $clear_money;
                $result['type'] = $result['type'] ?? 1;
            }
        }

        //判断是否需要 总游戏 盈亏判定
        //为false || 或者为盈利
        if (!$result['status'] || $diff >= 0) {
            $result = $this->checkGameWhole($user_id);
        }
        return $result;

    }

    /**
     * @return mixed 先不优化
     */
    private function getCheckData()
    {
        $redis_key = CacheKey::getDrawCheckKey($this->set_type);
        if ($this->redis->exists($redis_key)) {
            return json_decode($this->redis->get($redis_key), true);
        }
        $check_data = $this->checkModel->with('gift:id,price,name,picture')->get()->toArray();
        $this->redis->set($redis_key, json_encode($check_data));
        return $check_data;
    }

    private function checkGameWhole($user_id)
    {
        $result = ['status' => false];
        /*$whole_check_user = app('model_whole_game_check_user')->where('user_id', $user_id)->first();
        $whole_check_diff = $whole_check_user->output_week - $whole_check_user->input_week;*/

        $whole_check_user = $this->redis->hgetall($this->wholePrefix . CacheKey::USER_WEEK_PUT_RECORD . ":$user_id" . "_" . date("Y-W"));
        if (empty($whole_check_user)) {
            return $result;
        }
        $whole_check_diff = $whole_check_user['output'] - $whole_check_user['input'];
        if ($whole_check_diff >= 0) {
            return $result;
        }

        $whole_check_data = app('model_whole_game_check_repair')
            ->from(app('model_whole_game_check_repair')->getTable().' as cr')
            ->leftJoin(app('model_whole_game_check')->getTable().' as c', 'c.id', '=', 'cr.check_id')
            ->where(['c.type' => 2, ['c.money', '>=', $whole_check_diff], 'cr.set_type' => $this->set_type])
            ->selectRaw('cr.*,c.money,c.is_repeat,c.type')
            ->with(['gift:id,price,name,picture'])->orderBy('c.money', 'asc')->get()->toArray();

        if (!empty($whole_check_data)) {
            $where = ['user_id' => $user_id];
            $whole_check_record = app('model_whole_game_check_record')->where($where)->distinct()->pluck('check_id');
            foreach ($whole_check_data as $check) {
                //不是重复触发
                if(!$check['is_repeat']) {
                    $is_exist = $whole_check_record->contains($check['check_id']);
                    if ($is_exist) {
                        continue;
                    }
                }
                //防止后台的配置经过更改、记录最初值
                $result = [
                    'status' => true,
                    'gift_info' => $check['gift'] ?: [],
                    'count' => 0,
                    'check_id' => $check['check_id'],
                    'money' => $check['money'],
                    'set_type' => $this->set_type,
                    'check_repair_id' => $check['id'],
                    'type' => $check['type'],
                    'is_repeat' => $check['is_repeat'],
                    'clear_money' => 0,
                    'is_whole' => 1,
                ];
                break;
            }
        }
        return $result;
    }

    #判断用户是否可以出礼物，返回不出的礼物  礼物阈值
    public function checkBigGift($user_id)
    {
        $input_week = $this->redis->hget($this->set_type.':' . CacheKey::USER_WEEK_PUT_RECORD . ":$user_id" . "_" . date("Y-W"), 'input') ?: 0;

        $giftConfigList = $this->getGiftConfigCache();
        //为空 || 设置的空集合
        if (empty($giftConfigList) || isset($giftConfigList[0])) {
            return [];
        }
        $gift_template_ids = [];
        foreach ($giftConfigList as $k => $v) {
            if ($k > $input_week) {
                $gift_template_ids = array_merge($gift_template_ids, explode(',', $v));
            }
        }
        return $gift_template_ids;

        //周投入判断
        /*$gift_ids = $this->giftConfigModel->where([
            ['money', '>', $input_week],
            'is_open' => 1,
        ])->value(DB::Raw('GROUP_CONCAT(gift_ids)'));
        $gift_ids = explode(',' , $gift_ids);
        return $this->giftTemplateModel->whereIn('gift_id', $gift_ids)->pluck('id')->toArray();*/
    }

    private function getGiftConfigCache()
    {
        $redis_key = CacheKey::getGiftConfigKey($this->set_type);
        if ($this->redis->exists($redis_key)) {
            return $this->redis->hgetall($redis_key);
        }
        $giftConfigList = $this->giftConfigModel->where(['is_open' => 1])
            ->orderBy('money', 'asc')->pluck('gift_ids', 'money')->toArray();

        $list = [];
        foreach ($giftConfigList as $k => &$v) {
            $v = $this->giftTemplateModel->whereIn('gift_id', $v)->pluck('id')->implode(',');
            if (empty($v)) {
                continue;
            }
            $list[$k] = $v;
        }
        if (empty($list)) {
            $list = [0 => 0];
        }
        $this->redis->hmset($redis_key, $list);
        return $list;
    }

    public function list($params = [])
    {
        $game_type = $this->game_type;
        $prePage = $params['prePage'] ?? 20;
        $list = $this->addPoolConfigModel
            ->with(['relation:id,name', 'admin:auth_id,name'])
            ->orderBy('id', 'desc')->paginate($prePage)->toArray();
        $list['sup']['game_account'] = $this->addPoolAccountModel->where('game_type', $game_type)->value('money');
        return $list;
    }

    public function save($params)
    {
        $game_type = $this->game_type;
        $relation_model = $this->poolGroupModel;
        $config_model = $this->addPoolConfigModel;
        $pool_group = $relation_model->where('id', $params['relation_id'])->with('pool:id,tag')->first();
        $relation_type = $relation_model->getNameSpace();
        $save = [
            'relation_id' => $params['relation_id'],
            'relation_type' => $relation_type,
            'tag' => $pool_group->pool->tag,
            'rate' => $params['rate'],
            'add_money' => $params['add_money'],
            'game_type' => $game_type,
            'admin_id' => $params['admin_id'],
        ];
        if ($params['id']) {
            $config_model->where('id', $params['id'])->update($save);
        } else {
            $exist = $config_model->where([
                'game_type' => $game_type,
                'tag' => $pool_group->pool->tag,
                'relation_id' => $params['relation_id'],
            ])->count();
            if ($exist) {
                throw new BasicException('-1', '添加模板重复');
            }
            $config_model->insert($save);
        }
        return [
            'code' => 200,
        ];
    }

    public function delete($id)
    {
        return $this->addPoolConfigModel->where('id', $id)->delete();
    }

    public function checkList($params = [])
    {
        $prePage = $params['prePage'] ?? 20;
        $list = $this->checkModel
            ->with(['gift:id,name,price', 'admin:auth_id,name'])
            ->orderBy('id', 'desc')->paginate($prePage);
        return $list;
    }

    public function checkSave($params)
    {
        $type = $params['money'] > 0 ? 1 : 2;
        $save = [
            'money' => $params['money'],
            'type' => $type,
            'gift_id' => $params['gift_id'] ?? 0,
            'count' => $params['count'] ?? 0,
            'is_repeat' => $params['is_repeat'],
            'admin_id' => $params['admin_id'],
        ];
        if ($params['id']) {
            $this->checkModel->where('id', $params['id'])->update($save);
        } else {
            $this->checkModel->insert($save);
        }
        $this->redis->del(CacheKey::getDrawCheckKey($this->set_type));
        return true;
    }

    public function checkDelete($id)
    {
        return $this->checkModel->where('id', $id)->delete();
    }

    //修改补池金额
    public function changeGameAccount($params)
    {
        $game_type = $this->game_type;
        if (!empty($params['add_money'])) {
            //1.增加
            if ($params['type'] == 1) {
                $add_money = $params['add_money'];
            } else {
                $add_money = 0 - $params['add_money'];
            }
            $this->addPoolAccountRecordModel->addRecord([
                'game_type' => $game_type,
                'add_money' => $add_money,
                'config_id' => -1,
                'admin_id' => $params['admin_id'],
            ]);
        }
        return true;
    }

    public function getGameAccount($game_type = 2)
    {
        $game_type = $this->game_type;
        $result = $this->addPoolAccountModel->where('game_type', $game_type)->first();
        return $result;
    }

    //获得判定记录
    public function getCheckRecord($params)
    {
        $prePage = $params['prePage'] ?? 20;
        $where = [];
        if (!empty($params['user_code'])) {
            $user_id = app('model_user_data')->where('user_code', $params['user_code'])->value('user_id');
            $where['user_id'] = $user_id;
        }
        if (!empty($params['type'])) {
            $where['type'] = $params['type'];
        }
        $list = $this->checkRecordModel
            ->where($where)
            ->with(['gift:id,name', 'user_data:user_id,user_code,nickname'])
            ->orderBy('id', 'desc')->paginate($prePage);
        return $list;
    }


    //获得补池金额记录
    public function getAddPoolAccountRecord($params)
    {
        $config_type_ary = [
            2 => -1,//后台变动
            3 => 0,//补偿减少
            4 => -2,//补偿减少-总判定
        ];
        $prePage = $params['prePage'] ?? 20;
        $where = [];
        if (!empty($params['config_type'])) {
            if (isset($config_type_ary[$params['config_type']])) {
                $where['config_id'] = $config_type_ary[$params['config_type']];
            } else {
                $where[] = ['config_id', '>', 0];
            }
        }
        $config_id_ary = array_flip($config_type_ary);
        $list = $this->addPoolAccountRecordModel
            ->where($where)->with(['admin:auth_id,name'])
            ->orderBy('id', 'desc')->paginate($prePage)->toArray();
        foreach ($list['data'] as &$value) {
            if (isset($config_id_ary[$value['config_id']])) {
                $config_type = $config_id_ary[$value['config_id']];
            } else {
                $config_type = 1;//'策略增加'
            }
            $value['config_type'] = $config_type;
        }
        return $list;
    }

    public function getGiftConfig($params)
    {
        $prePage = $params['prePage'] ?? 20;
        $list = $this->giftConfigModel->with(['admin:auth_id,name'])
            ->orderBy('id', 'desc')->paginate($prePage)->toArray();
        $giftModel = app('model_gift');
        foreach ($list['data'] as &$value) {
            $value['gift_names'] = $giftModel->whereIn('id', $value['gift_ids'])->selectRaw("GROUP_CONCAT(name,'(',price,'金币)') name")->pluck('name')->implode(',');
        }

        return $list;
    }

    public function setGiftConfig($params)
    {
        $data = $this->giftConfigModel;
        if ($params['id']) {
            $data = $this->giftConfigModel->where('id', $params['id'])->first();
        }

        $save = [
            'money' => $params['money'],
            'gift_ids' => $params['gift_ids'] ?? '',
            'is_open' => $params['is_open'],
            'admin_id' => $params['admin_id'],
        ];
        $data->fill($save);
        $data->save();
        $this->redis->del(CacheKey::getGiftConfigKey($this->set_type));
        return true;
    }

    public function getAppointGift($params)
    {
        $prePage = $params['prePage'] ?? 20;
        $user_no = $params['user_no'] ?? '';
        $is_valid = $params['is_valid'] ?? '';
        $type = $params['type'] ?? '';
        $where = [];
        if (!empty($user_no)) {
            $user_id = app('model_user_data')->where('user_code', $user_no)->value('user_id');
            $where['user_id'] = $user_id;
        }
        if (!empty($is_valid)) {
            $where['is_valid'] = $is_valid;
        }
        if (!empty($type)) {
            $where['type'] = $type;
        }
        $list = $this->appointGiftModel->where($where)->with([
            'user_data:user_id,nickname,user_code', 'gift:id,name', 'admin:auth_id,name'
        ])->orderBy('id', 'desc')->paginate($prePage)->toArray();
        foreach ($list['data'] as &$value) {
            $value['user_code'] = $value['user_data']['user_code'];
        }

        return $list;
    }

    public function setAppointGift($params)
    {
        $data = $this->appointGiftModel;
        if ($params['id']) {
            $data = $this->appointGiftModel->where('id', $params['id'])->first();
        }
        if (!empty($params['user_code'])) {
            $params['user_id'] = app('model_user_data')->where('user_code', $params['user_code'])->value('user_id');
        }
        if (empty($params['user_id'])) {
            throw new BasicException('-1', '该用户不存在');
        }

        $save = [
            'user_id' => $params['user_id'],
            'gift_id' => $params['gift_id'] ?? '',
            'is_valid' => $params['is_valid'],
            'admin_id' => $params['admin_id'],
        ];
        $data->fill($save);
        $data->save();
//        $this->setAppointGiftRedis($data);
        return true;
    }

    private function setAppointGiftRedis($data)
    {
        $redis_key = CacheKey::getAppointGiftKey($this->set_type);
        if ($this->redis->exists($redis_key)) {
            if ($data['is_valid'] == 1) {
                $gift_template_id = $this->giftTemplateModel->where('gift_id', $data['gift_id'])->value('id');
                if ($gift_template_id) {
                    $this->redis->hset($redis_key, $data['id'].'_'.$data['user_id'], $gift_template_id);
                }
            }
        } else {
            $list = $this->giftTemplateModel
                ->from($this->giftTemplateModel->getTable() . " as b")
                ->leftjoin($this->appointGiftModel->getTable().' as a', 'b.gift_id', '=', 'a.gift_id')
                ->where('a.is_valid', 1)
                ->groupBy('a.id')
                ->selectRaw("b.id gift_template_id,GROUP_CONCAT(a.id,'_',a.user_id) concat_id")->get()->toArray();
            if (!empty($list)) {
                $this->redis->hmset($redis_key, $list);
            }
        }
    }


    public function getWholeGameUser($params)
    {
        $where = [];
        $prePage = $params['prePage'] ?? 20;
        $user_code = $params['user_code'] ?? 0;
        $list = app('model_whole_game_check_user')->with([
            'user_data:user_id,nickname,user_code'
        ]);
        if (!empty($user_code)) {
            $user_ids = app('model_user_data')->where('user_code', $user_code)->pluck('user_id')->toArray();
            $list->whereIn('user_id', $user_ids);
        }
        $list = $list->orderBy('user_id', 'desc')->where($where)->paginate($prePage)->toArray();
        foreach ($list['data'] as &$value) {
            $value['user_code'] = $value['user_data']['user_code'];
            $value['nickname'] = $value['user_data']['nickname'];
            $value['dayTotal'] = $value['input_date'] - $value['output_date'];
            $value['weekTotal'] = $value['input_week'] - $value['output_week'];
            $value['total'] = $value['input'] - $value['output'];
        }
        return $list;

    }

    public function getWholeGameCheckList($params = [])
    {
        $prePage = $params['prePage'] ?? 20;
        $list = app('model_whole_game_check')
            ->with(['check_repair'])
            ->orderBy('id', 'desc')->paginate($prePage)->toArray();

        foreach ($list['data'] as &$value) {
            $value['pet'] = $value['senior'] = $value['stellar'] = '';
            foreach ($value['check_repair'] as $repair) {
                $value[$repair['set_type']] = $repair['gift_id'];
            }
//            unset($value['repair']);
        }
        return $list;
    }

    public function wholeGameCheckSave($params)
    {
        $type = $params['money'] > 0 ? 1 : 2;
        $model = app('model_whole_game_check');
        $save = [
            'money' => $params['money'],
            'type' => $type,
            'is_repeat' => $params['is_repeat'],
        ];
        if ($params['id']) {
            $model->where('id', $params['id'])->update($save);
        } else {
            $params['id'] = $model->insertGetId($save);
        }
        $saveMany = $insertMany = [];
        $repair_model = app('model_whole_game_check_repair');
        $repair_list = $repair_model->where('check_id', $params['id'])->get()->toArray();
        $repair_list = array_column($repair_list, NULL, 'set_type');
        $setTypeList = ['pet', 'stellar', 'senior', 'gashapon', 'fantasy'];
        foreach ($setTypeList as $set_type) {
            $many_data = [
                'check_id' => $params['id'],
                'gift_id' => $params[$set_type],
                'set_type' => $set_type,
            ];
            if (isset($repair_list[$set_type])) {
                $saveMany[$repair_list[$set_type]['id']] = $many_data;
            } else {
                $insertMany[] = $many_data;
            }
        };

        if (!empty($insertMany)) {
            $repair_model->insert($insertMany);
        }
        if (!empty($saveMany)) {
            foreach ($saveMany as $repair_id => $many) {
                $repair_model->where('id', $repair_id)->update($many);
            }
        }
        return true;
    }

    public function wholeGameCheckDelete($id)
    {
        app('model_whole_game_check')->where('id', $id)->delete();
        app('model_whole_game_check_repair')->where('check_id', $id)->delete();
        return true;
    }


    public function getWholeGameCheckRecord($params)
    {
        $prePage = $params['prePage'] ?? 20;
        $where = [];
        if (!empty($params['user_code'])) {
            $user_id = app('model_user_data')->where('user_code', $params['user_code'])->value('user_id');
            $where['user_id'] = $user_id;
        }
        $list = app('model_whole_game_check_record')
            ->where($where)
            ->with(['gift:id,name', 'user_data:user_id,user_code,nickname'])
            ->orderBy('id', 'desc')->paginate($prePage);
        return $list;
    }


}
